from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from django.contrib.auth import authenticate
from django.contrib.auth.decorators import login_required
from django.core.handlers.wsgi import WSGIRequest
from django.utils.timezone import now
from django.db.models.query import QuerySet
from rest_framework import permissions, viewsets, status, views, generics
from rest_framework.response import Response
from rest_framework.request import Request
from rest_framework.versioning import BaseVersioning
from rest_framework.decorators import action
import celery
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from rest_framework.decorators import api_view

from .serializers import GroupSerializer, UserSerializer
from .permissions import IsOwnerOrReadOnly
from .models import Group, User
from .auth import MyAuthentication
from .tasks import add, mul


class UserViewSet(viewsets.ModelViewSet):
    # class UserViewSet(viewsets.ReadOnlyModelViewSet):
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    # permission_classes = [permissions.IsAuthenticated]
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    # authentication_classes = [MyAuthentication]

    # def check_permissions(self):
    #     ...

    # action: add a new view func with url
    @action(methods=['get'], detail=False)
    def login(self, request, *args, **kwargs):
        print('request.site', request.site)
        return Response({'code': '200', 'msg': 'login ok'})

    @action(methods=['post', 'get'], detail=False)
    def logout(self, request, *args, **kwargs):
        # call tasks method 1
        # add.delay(3, 5)
        # mul.delay(6, 8)
        # call tasks method 2
        # celery.app.task.Task
        # celery.result.AsyncResult
        res1 = add.apply_async(args=(3, 5))
        print(res1.task_id, res1.status, res1.result)
        res2 = mul.apply_async(args=(6, 8))
        print(res2.task_id, res2.status, res2.result)

        # from time import sleep
        # sleep(5)
        return Response({'code': '200', 'msg': 'logout ok'})


class GroupViewSet(viewsets.ModelViewSet):
    queryset = Group.objects.all().order_by('name')
    serializer_class = GroupSerializer
    # permission_classes = [permissions.IsAuthenticated]
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    # permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]  # group add permission


# 为原生django添加api文档!!!
@swagger_auto_schema(
    method='get',
    responses={
        200: openapi.Response('A successful response', schema=openapi.Schema(type=openapi.TYPE_OBJECT, properties={'message': openapi.Schema(type=openapi.TYPE_STRING)})),
        400: "无效请求",
    }
)
@api_view(['GET'])
def index(request: WSGIRequest):
    return JsonResponse({'msg': 'index'})
